import { Injectable } from '@angular/core';
import { EventService, EventMessage, EventSource } from '../services/event.service'
import { RequestReplyService } from '../services/request-reply.service'
import { OrtcService, XMPPMessage} from '../services/ortc.service'

import { User, AuthUser } from '../entity/TT';
import { Type, Message, TextMessage } from '../entity/Chat'
import { CONNECTION_STATUS } from '../entity/ORTC';

@Injectable({
  providedIn: 'root'
})
export class ChatService {
  private isInited: boolean = false;
  
  constructor(
    private eventService: EventService,
    private requestService: RequestReplyService,
    private rtcservice: OrtcService) { }
  
  
  init(user: User) {
    console.log("chat init...", this.isInited)
    if(this.isInited){
      console.warn("isInited!")
      return;
    }
    if (!user) {
      console.error("user is invalid!")
      return
    }
    try{
      this.isInited = true;
  
      this.requestService.GetPassword().subscribe((pwd) => {
        if (!pwd) {
          console.log("pwd is invalid!")
          return
        }
        //初始化jitsi
        this.rtcservice.init(AuthUser.from(user, pwd));
      })
  
      let emit = this.eventService.emit;
      emit.subscribe((evt: EventMessage) => {
    
        switch (evt.source) {
          case EventSource.XMPP_MESSAGE:
            let msg: XMPPMessage = evt.data;
            let m = this.transformMessage(msg);
            this.eventService.sendMessage(m);
            break;
  
          case EventSource.XMPP_CONNECTION_STATUS:
            let status: CONNECTION_STATUS = evt.data;
            if (status == CONNECTION_STATUS.ESTABLISHED) {
              //获取当前conference
              this.requestService.GetConference().subscribe((jid: string) => {
                this.rtcservice.joinConference(jid)
              })
            }
            break;
        }
      })
    }catch(e){
      this.isInited = false;
      console.error("init ", e)
    }
    

    
  }

  destory(){
    console.log("destory ...")
  }

  transformMessage(xmpp: XMPPMessage): TextMessage {

    let uin = this.getUinFromMsgId(xmpp.id);

    let msg: TextMessage = {
      id: xmpp.id,
      time: xmpp.ts,
      avatar: { url: '', uin: uin, name: '' },
      text: xmpp.text,
    }

    return msg;
  }

  getUinFromMsgId(msgId: string) {
    // g0000000001-9682dc
    return msgId.split("-")[0]
  }

  // getMessageList(bookedId: number): Observable<object[]> {

  //   console.log('getMessageList', bookedId)

  //   // return this.requestService.GetReply(this.listMessageUrl, { bookedId }).pipe(
  //   //   map(reply => {
  //   //     if (reply.success) {
  //   //       return reply.data;
  //   //     }
  //   //     else
  //   //       console.error("error", reply.data);
  //   //   })
  //   // )
  // }


  sendMessage(text: string): boolean {
    return this.rtcservice.sendText(text);
  }

}
